global root_dir = "`1'"

include "$root_dir/code/config/config.do"

cap noi log using ${log_dir}/fig_A1_data.log, replace name(dat)

*Handle empty arguments
global arg1 = cond("`2'" == "___EMPTY___", "", "`2'")
global arg2 = cond("`3'" == "___EMPTY___", "", "`3'")
global arg3 = cond("`4'" == "___EMPTY___", "", "`4'")
global arg4 = cond("`5'" == "___EMPTY___", "", "`5'")

if "$arg1" != "" {
    global weight_category "$arg1"
    di "Weight category: ${weight_category}"
}

if "$arg2" != "" {
    global weight_versions "$arg2"
    di "Weight versions: ${weight_versions}"
}

if "$arg3" != "" {
    global weight_window "$arg3"
    di "Weight window: ${weight_window}"
}

if "$arg4" != "" {
	global wtype "$arg4"
}
di "${wtype}"

capture noi {

    *first get the patents per year via applications
    use appln_id appln_year using ${commondata_dir}/patstat_2018b/appln_info.dta, clear
    mmerge appln_id  using ${commondata_dir}/patstat_2018b/family_info.dta, unmatched(none) ukeep(docdb_family_id)
    mmerge docdb_family_id using ${dataset_dir}/patstat_orbis/docdb_families2.dta, unmatched(master) ukeep(biadic_D)
    keep if biadic_D
    keep appln_id  appln_year docdb_family_id

    mmerge appln_id using ${commondata_dir}/patstat_2018b/appln_id_techn_field.dta, unmatched(none)
    drop _m
    keep appln_year techn_field_nr weight

    *now we know how many patents there are per technology field per year
    collapse (sum)weight, by(techn_field_nr appln_year)
    compress

    ren weight patents

    *restrcit timeframe
    keep if appln_year >= 1997
    keep if appln_year <= 2011
    collapse (sum)patents, by(techn_field_nr)

    mmerge techn_field_nr using ${commondata_dir}/patstat_2018b/techn_fields.dta, unmatched(master)
    egen totpats = sum(patents)
    gen share = patents/totpats*100
    drop _m

    save ${final_dir}/fig_A1_data.dta, replace


}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close dat